// 终端实例
let terminal;
let fitAddon;
let webSocket;
let isConnected = false;

// 初始化终端
function initTerminal() {
    // 创建终端实例
    terminal = new Terminal({
        cursorBlink: true,
        cursorStyle: 'block',
        fontSize: 14,
        fontFamily: 'Consolas, "Courier New", monospace',
        theme: {
            background: '#1e1e1e',
            foreground: '#d4d4d4',
            cursor: '#ffffff',
            selection: '#264f78',
            black: '#000000',
            red: '#cd3131',
            green: '#0dbc79',
            yellow: '#e5e510',
            blue: '#2472c8',
            magenta: '#bc3fbc',
            cyan: '#11a8cd',
            white: '#e5e5e5',
            brightBlack: '#666666',
            brightRed: '#f14c4c',
            brightGreen: '#23d18b',
            brightYellow: '#f5f543',
            brightBlue: '#3b8eea',
            brightMagenta: '#d670d6',
            brightCyan: '#29b8db',
            brightWhite: '#e5e5e5'
        },
        cols: 80,
        rows: 24
    });

    // 添加插件
    fitAddon = new FitAddon.FitAddon();
    const webLinksAddon = new WebLinksAddon.WebLinksAddon();
    
    terminal.loadAddon(fitAddon);
    terminal.loadAddon(webLinksAddon);

    // 打开终端
    terminal.open(document.getElementById('terminal'));
    
    // 调整终端大小
    fitAddon.fit();

    // 显示欢迎信息
    showWelcomeMessage();

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
        fitAddon.fit();
    });

    // 监听终端输入
    terminal.onData(data => {
        if (webSocket && webSocket.readyState === WebSocket.OPEN) {
            webSocket.send(JSON.stringify({
                type: 'input',
                data: data
            }));
        }
    });
}

// 显示欢迎信息
function showWelcomeMessage() {
    const welcomeText = `
\r\n🐧 欢迎使用 Linux容器 Web终端\r\n
\r\n📋 使用说明：\r\n
\r\n  1. 点击 "🔗 连接SSH" 按钮连接到Linux容器\r\n
\r\n  2. 使用以下账户登录：\r\n
\r\n     👤 用户名: developer\r\n
\r\n     🔑 密码: dev123\r\n
\r\n  3. 登录后即可使用完整的Linux命令行环境\r\n
\r\n💡 提示：\r\n
\r\n  • 支持所有标准Linux命令\r\n
\r\n  • 支持文件编辑 (vim, nano)\r\n
\r\n  • 支持软件包管理 (apt)\r\n
\r\n  • 具有sudo权限\r\n
\r\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\r\n
\r\n`;
    
    terminal.write(welcomeText);
}

// 连接SSH
function connectSSH() {
    if (isConnected) {
        terminal.write('\r\n⚠️  已经连接到服务器\r\n');
        return;
    }

    updateStatus('connecting', '连接中...');
    showLoading(true);
    
    terminal.clear();
    terminal.write('🔄 正在连接到 Linux容器...\r\n');
    terminal.write('📡 服务器: localhost:2222\r\n');
    terminal.write('👤 用户: developer\r\n');
    terminal.write('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\r\n\r\n');

    // 模拟SSH连接过程
    setTimeout(() => {
        terminal.write('🔐 正在进行SSH握手...\r\n');
        
        setTimeout(() => {
            terminal.write('✅ SSH连接建立成功\r\n');
            terminal.write('🔑 请输入密码进行身份验证\r\n\r\n');
            
            // 模拟登录提示
            setTimeout(() => {
                terminal.write('developer@localhost\'s password: ');
                
                // 模拟密码输入（实际应该通过WebSocket处理）
                let passwordInput = '';
                const originalOnData = terminal.onData;
                
                terminal.onData = (data) => {
                    if (data === '\r') {
                        // 回车键，验证密码
                        if (passwordInput === 'dev123') {
                            terminal.write('\r\n\r\n✅ 登录成功！\r\n\r\n');
                            showLoginSuccess();
                            updateStatus('connected', '已连接');
                            isConnected = true;
                            showLoading(false);
                            
                            // 恢复正常输入处理
                            terminal.onData = originalOnData;
                        } else {
                            terminal.write('\r\n❌ 密码错误，请重试\r\n');
                            terminal.write('developer@localhost\'s password: ');
                            passwordInput = '';
                        }
                    } else if (data === '\u007f') {
                        // 退格键
                        if (passwordInput.length > 0) {
                            passwordInput = passwordInput.slice(0, -1);
                        }
                    } else if (data.charCodeAt(0) >= 32) {
                        // 可打印字符
                        passwordInput += data;
                        terminal.write('*'); // 显示星号
                    }
                };
                
            }, 1000);
        }, 1500);
    }, 1000);
}

// 显示登录成功信息
function showLoginSuccess() {
    const loginText = `
Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 5.15.0-88-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

Last login: ${new Date().toLocaleString()}

developer@linux-basic:~$ `;
    
    terminal.write(loginText);
    
    // 恢复正常的命令行交互
    setupCommandLine();
}

// 设置命令行交互
function setupCommandLine() {
    let currentCommand = '';
    let commandHistory = [];
    let historyIndex = -1;
    
    terminal.onData(data => {
        const code = data.charCodeAt(0);
        
        if (code === 13) { // 回车键
            terminal.write('\r\n');
            
            if (currentCommand.trim()) {
                commandHistory.unshift(currentCommand);
                executeCommand(currentCommand.trim());
            } else {
                terminal.write('developer@linux-basic:~$ ');
            }
            
            currentCommand = '';
            historyIndex = -1;
            
        } else if (code === 127) { // 退格键
            if (currentCommand.length > 0) {
                currentCommand = currentCommand.slice(0, -1);
                terminal.write('\b \b');
            }
            
        } else if (code === 27) { // ESC序列（方向键等）
            // 处理方向键
            return;
            
        } else if (code >= 32) { // 可打印字符
            currentCommand += data;
            terminal.write(data);
        }
    });
}

// 执行命令
function executeCommand(command) {
    const cmd = command.toLowerCase().trim();
    
    // 模拟一些基本命令
    switch (cmd) {
        case 'ls':
        case 'ls -la':
        case 'll':
            terminal.write('total 28\r\n');
            terminal.write('drwxr-xr-x 1 developer developer 4096 Dec 22 10:30 .\r\n');
            terminal.write('drwxr-xr-x 1 root      root      4096 Dec 22 10:00 ..\r\n');
            terminal.write('-rw-r--r-- 1 developer developer  220 Dec 22 10:00 .bash_logout\r\n');
            terminal.write('-rw-r--r-- 1 developer developer 3526 Dec 22 10:00 .bashrc\r\n');
            terminal.write('-rw-r--r-- 1 developer developer  807 Dec 22 10:00 .profile\r\n');
            terminal.write('drwxrwxrwx 1 developer developer 4096 Dec 22 10:30 shared\r\n');
            break;
            
        case 'pwd':
            terminal.write('/home/developer\r\n');
            break;
            
        case 'whoami':
            terminal.write('developer\r\n');
            break;
            
        case 'date':
            terminal.write(new Date().toString() + '\r\n');
            break;
            
        case 'uname -a':
            terminal.write('Linux linux-basic 5.15.0-88-generic #98-Ubuntu SMP Mon Oct 2 15:18:56 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux\r\n');
            break;
            
        case 'clear':
            terminal.clear();
            terminal.write('developer@linux-basic:~$ ');
            return;
            
        case 'exit':
        case 'logout':
            terminal.write('logout\r\n');
            terminal.write('Connection to localhost closed.\r\n');
            disconnect();
            return;
            
        case 'help':
            terminal.write('可用命令：\r\n');
            terminal.write('  ls, ll     - 列出文件\r\n');
            terminal.write('  pwd        - 显示当前目录\r\n');
            terminal.write('  whoami     - 显示当前用户\r\n');
            terminal.write('  date       - 显示日期时间\r\n');
            terminal.write('  uname -a   - 显示系统信息\r\n');
            terminal.write('  clear      - 清屏\r\n');
            terminal.write('  exit       - 退出\r\n');
            terminal.write('  help       - 显示帮助\r\n');
            terminal.write('\r\n注意：这是一个演示版本，实际环境中会有更多命令可用。\r\n');
            break;
            
        default:
            if (cmd) {
                terminal.write(`bash: ${cmd}: command not found\r\n`);
                terminal.write('提示：输入 "help" 查看可用命令\r\n');
            }
            break;
    }
    
    terminal.write('developer@linux-basic:~$ ');
}

// 断开连接
function disconnect() {
    if (webSocket) {
        webSocket.close();
    }
    
    isConnected = false;
    updateStatus('disconnected', '未连接');
    showLoading(false);
    
    terminal.clear();
    terminal.write('🔌 连接已断开\r\n\r\n');
    showWelcomeMessage();
}

// 清屏
function clearTerminal() {
    terminal.clear();
    if (isConnected) {
        terminal.write('developer@linux-basic:~$ ');
    } else {
        showWelcomeMessage();
    }
}

// 更新连接状态
function updateStatus(status, text) {
    const statusElement = document.getElementById('status');
    statusElement.className = `status ${status}`;
    statusElement.textContent = text;
}

// 显示/隐藏加载动画
function showLoading(show) {
    const loadingElement = document.getElementById('loading');
    const terminalElement = document.getElementById('terminal');
    
    if (show) {
        loadingElement.classList.add('show');
        terminalElement.style.opacity = '0.3';
    } else {
        loadingElement.classList.remove('show');
        terminalElement.style.opacity = '1';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initTerminal();
    
    // 检查容器是否运行
    checkContainerStatus();
});

// 检查容器状态
function checkContainerStatus() {
    // 这里可以添加检查Docker容器是否运行的逻辑
    // 暂时显示提示信息
    setTimeout(() => {
        terminal.write('\r\n💡 提示：请确保Linux容器已启动\r\n');
        terminal.write('   运行命令：cd docker/linux-basic && docker-compose up -d\r\n\r\n');
    }, 2000);
}

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    // Ctrl+C 清屏
    if (e.ctrlKey && e.key === 'c') {
        e.preventDefault();
        if (isConnected) {
            terminal.write('^C\r\ndeveloper@linux-basic:~$ ');
        }
    }
    
    // Ctrl+D 断开连接
    if (e.ctrlKey && e.key === 'd') {
        e.preventDefault();
        if (isConnected) {
            disconnect();
        }
    }
});